package web;

import com.google.gson.Gson;
import pojo.User;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.webUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //调用userService.Login()处理登录业务
        User loginUser = userService.login(new User(null, username, null, password, 0));
        //如果等于null，说明登录失败，跳回登录页面
        if (loginUser == null) {
            //把错误信息和回显的表单项信息，保存到request域中
            req.setAttribute("msg","用户名或密码错误！");
            req.setAttribute("username",username);
            //跳回登录页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        }else {
            //登录成功
            //保存用户登录的信息到Session域中
            req.getSession().setAttribute("user",loginUser);
            //登陆成功，跳到login_success.html页面
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        }
    }
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取Session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除Session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        //1.获取请求的参数
        String username = req.getParameter("username");
        String gender = req.getParameter("gender");
        String password = req.getParameter("password");
        int status = webUtils.parseInt(req.getParameter("status"),1);
        String code = req.getParameter("code");
//        User user = webUtils.copyParamToBean(req.getParameterMap(),new User());
        //2.检查验证码是否正确
        if (token != null && token.equalsIgnoreCase(code)) {
            //正确
            //3.检查用户名是否可用
            if(userService.existsUsername(username)){
                //把回显信息，保存到Request域中
                req.setAttribute("msg","用户名已存在!");
                req.setAttribute("username",username);
                req.setAttribute("gender",gender);
                req.setAttribute("status",status);

                //不可用，跳回注册页面
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
            }else {
                //可用，调用Service保存到数据库
                userService.regisUser(new User(null, username, gender, password, status));
                //跳到登录页面login.jsp
                req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
            }

        }else {
            //不正确
            //把回显信息，保存到Request域中
            req.setAttribute("msg","验证码错误!");
            req.setAttribute("username",username);
            req.setAttribute("gender",gender);
            req.setAttribute("status",status);
            //返回注册页面
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }

    //处理注销的功能
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.销毁Session中用户登录的信息（或者销毁Session）
        req.getSession().invalidate();
        //2.重定向到首页（或登录界面）
        resp.sendRedirect(req.getContextPath());
    }

    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数username
        String username = req.getParameter("username");
        //调用userService.existsUsername();
        boolean existsUsername = userService.existsUsername(username);
        //把返回的结果封装成map对象
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("existsUsername",existsUsername);

        Gson gson = new Gson();
        String json = gson.toJson(resultMap);

        resp.getWriter().write(json);
    }
}
